import json

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.http import HttpResponseForbidden
from django.http import HttpResponseNotFound
from django.http import HttpResponseServerError
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.contents.fengzhuang import get_categories
from apps.goods import models
from apps.goods.models import SKU
from apps.goods.utils.breadcrumb import get_breadcrumb
from apps.orders.models import OrderGoods, OrderInfo
from apps.shoppingcart import easy_shopping
from utils.response_code import RETCODE

#列表页
from utils.superjiajiemi import jiajiemiSuper


class ListView(View):
    def get(self, request, category_id, page_num):
        #接收数据
        category_id = category_id
        page_num = page_num
        #如果不存在则使用默认排序
        sort = request.GET.get('sort','default')
        #检查数据
        try:
            category=models.GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            print(e)
            return http.HttpResponseNotFound('GoodsCategory does not exist')


        #调用封装的商品频道表
        categories = get_categories()
        breadcrumb = get_breadcrumb(category)

        #按照排序规则查询SKU信息
        if sort =='price':
            sort_field='price'
        elif sort =='hot':
            sort_field='-sales'
        else:
            #如果没有按销量和热度排行则使用默认时间
            sort_field='create_time'
        skus = models.SKU.objects.filter(category=category,is_launched=True).order_by(sort_field)

        #分页器,每页N条记录,创建分页器实例
        paginator = Paginator(skus,5)
        try:
            #page_num当前页数,page_skus是当前页数的内容
            page_skus = paginator.page(page_num)
        except Exception:
            return http.HttpResponseNotFound('empty page')
        total_page = paginator.num_pages

        shoppingcart, amount = easy_shopping.easy_shopping(request)


        context = {
            'categories':categories,#频道表
            'breadcrumb':breadcrumb,#面包屑导航
            'sort':sort,#用户所需排序
            'category':category, #三级对象
            'page_skus':page_skus, #当前页数的内容
            'total_page':total_page,#总页数
            'page_num':page_num,   #当前页
            'shoppingcart':shoppingcart,
            'amount':amount

        }
        return render(request,'list.html',context)


#热销排行
class HotView(View):

    def get(self,request,category_id):
        category_id = category_id
        #category_id????
        skus = models.SKU.objects.filter(category=category_id).order_by('-sales')[:2]
        hot_skus=[]
        #需要有个列表来添加
        for sku in skus:
            hot_skus.append({
                'name':sku.name,
                'price':sku.price,
                'id':sku.id,
                'default_image_url':sku.default_image.url
            })
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'hot_skus':hot_skus})


#商品详情页
class DetailView(View):
    #需要接受一个商品id号
    def get(self,request,sku_id):
        user = request.user
        #获取sku_id对应商品,和数据库有联系要用异常处理
        try:
            sku =models.SKU.objects.get(id=sku_id)
        except Exception:
            return render(request, '404.html')
        #商品分类
        categories = get_categories()
        #面包屑导航
        breadcrumb = get_breadcrumb(sku.category)
        #热销排行直接让网页请求其方法路由

        # '''----------------------评价----------------------'''
        #获得该商品全部的评价和用户  ,如果是匿名评价则不显示用户名
        comments = []
        #然后通过该记录获得order_id来获得用户
        commented_goods = OrderGoods.objects.filter(sku_id=sku_id,is_commented=True)
        comment_count = 0
        for commented_good in commented_goods:
            comment_count += 1
            comment = commented_good.comment
            #评价需要对应用户 ,根据order_id 去找用户
            if commented_good.is_anonymous == True:
                comments.append({'匿名用户':comment})
            else:
                order_id = commented_good.order_id
                #订单可能有多个商品,但只有一个用户,不 只有一个订单 订单号唯一
                good_user = OrderInfo.objects.get(order_id=order_id).user.username
                comments.append({good_user:comment})

# '''-------封装的简易购物车------'''
        shoppingcart,amount= easy_shopping.easy_shopping(request)






        context = {
            'sku':sku
            ,"categories":categories
            ,'breadcrumb':breadcrumb,
            'comments':comments,
            'comment_count':comment_count,
            'shoppingcart':shoppingcart,
            'amount':amount
        }
        return render(request,'detail.html',context)

#商品访问量

class DetailVisitView(View):

    def post(self,request,category_id):
        category_id=category_id
        try:
            category = models.GoodsCategory.objects.get(id=category_id)
        except Exception:
            return HttpResponseNotFound('缺少必传参数')

        #如果存在这个类别
        from datetime import  datetime
        today_str = datetime.now().strftime('%Y-%m-%d')
        today_date = datetime.strptime(today_str,'%Y-%m-%d')
        print(today_str)
        from apps.goods.models import GoodsVisitCount

        try:
            count_data = models.GoodsVisitCount.objects.get(date=today_date)
        except Exception:
            #如果没有创建
            count_data = GoodsVisitCount()


        try:
            count_data.count +=1
            count_data.category = category
            count_data.save()
        except Exception:
            return HttpResponseServerError('新增失败')
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

#保存用户浏览记录
class UserBrowseHistory(LoginRequiredMixin, View):
    #在进入每个详情页的时候会自动发送请求,加载浏览记录
    def post(self,request):
        sku_id = json.loads(request.body.decode()).get('sku_id')

    #判断商品是否存在
        try:
            sku = models.SKU.objects.get(id=sku_id)
        except Exception:
            return HttpResponseForbidden('商品不存在!')
    #如果有sku,就保存到redis
        client = get_redis_connection('history')
        #用列表左进右出 ,用用户专属唯一id当作key
        #在添加之前先去重,全删再添加
        #利用管道
        p1 = client.pipeline()
        list_name = request.user.id
        client.lrem(list_name,0,sku_id)#删除这表中所有的sku_id
        client.lpush(list_name,sku_id)#添加
        client.ltrim(list_name,0,4)#截取5个
        p1.execute()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

    #在进入用户中心的时候会发起请求
    def get(self,request):
        #连接数据库
        list_name = request.user.id
        client = get_redis_connection('history')
        sku_ids = client.lrange(list_name,0,4) #取出来的是sku_id
        brows_list =  []
        for sku_id in sku_ids:
            #根据sku_id获得sku商品对象
            sku = models.SKU.objects.get(id=sku_id)
            brows_list.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': brows_list})



#
